package org.trajectory.dao;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.pentaho.commons.connection.IPentahoConnection;
import org.pentaho.platform.api.engine.IPentahoSession;
import org.pentaho.platform.api.repository.datasource.DatasourceMgmtServiceException;
import org.pentaho.platform.api.repository.datasource.IDatasource;
import org.pentaho.platform.api.repository.datasource.IDatasourceMgmtService;
import org.pentaho.platform.engine.core.system.PentahoSessionHolder;
import org.pentaho.platform.engine.core.system.PentahoSystem;
import org.pentaho.platform.engine.services.connection.PentahoConnectionFactory;
import org.pentaho.platform.util.messages.Messages;

public class ConnectionService {
	private static final Log logger = LogFactory.getLog(ConnectionService.class);
	private IDatasourceMgmtService datasourceMgmtSvc;
	private IPentahoSession session;
	public ConnectionService(){
		session = PentahoSessionHolder.getSession();
	    this.datasourceMgmtSvc = ((IDatasourceMgmtService)PentahoSystem.get(IDatasourceMgmtService.class, session));
	}
	public List<IDatasource> getConnections() throws DatasourceMgmtServiceException
	  {
	   /* if (!hasDataAccessPermission()) {
	      logger.error(Messages.getErrorString("ConnectionServiceImpl.ERROR_0001_PERMISSION_DENIED"));
	      throw new ConnectionServiceException(Messages.getErrorString("ConnectionServiceImpl.ERROR_0001_PERMISSION_DENIED"));
	    }
*/
	    List connectionList = new ArrayList();
	    try {
	      for (IDatasource datasource : this.datasourceMgmtSvc.getDatasources())
	    	if(validate(datasource))
	    		connectionList.add(datasource);
	    }
	    catch (DatasourceMgmtServiceException dme) {
	      logger.error(Messages.getErrorString("ConnectionServiceImpl.ERROR_0002_UNABLE_TO_GET_CONNECTION_LIST", dme.getLocalizedMessage()));

	      throw dme;
	    }

	    return connectionList;
	  }
	public boolean validate(IDatasource datasource){
		IPentahoSession session = PentahoSessionHolder.getSession();
		IPentahoConnection connection = PentahoConnectionFactory.getConnection(IPentahoConnection.SQL_DATASOURCE, datasource.getName(), session, session);
		try {
			connection.executeQuery("select 1 from transaction;");
			return true;
		} catch (Exception e) {
			return false;
		}finally{
			if(connection != null)
				connection.close();
		}
	}
	
	public IPentahoConnection getConnection(String name){
		return PentahoConnectionFactory.getConnection(IPentahoConnection.SQL_DATASOURCE, name, session, session); 
	}
}
